using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;

namespace WebSMS;

public class UserRuleLinksService : ITerUserRuleLinks,ITransient
{
    private readonly IRepository<UserRuleLinks> _userRuleLinks;
    private readonly IRepository<UserPo> _users;
    private readonly IRepository<RulePo> _rules;
    
    public UserRuleLinksService(IRepository<UserRuleLinks> userRuleLinks,IRepository<UserPo> users,IRepository<RulePo> rules)
    {
        _userRuleLinks = userRuleLinks;
        _users = users;
        _rules = rules;
    }

    public List<UserRuleLinks> GetUserRuleByUserId(Guid guid)
    {
       return  _userRuleLinks.Where(x => x.RuleId == guid).ToList();
    }

    public async Task<bool> AddUserRule(UserRuleLinks userRuleLinks)
    {
        await _userRuleLinks.InsertNowAsync(userRuleLinks);
        return true;
    }

    public async Task<bool> DeleteUserRule(Guid userId,Guid ruleId)
    {
        await _userRuleLinks.FirstOrDefaultAsync(ur => ur.UserId == userId && ur.RuleId == ruleId);
        return true;
    }
    

    public IQueryable GetUserAndRuleList()
    {
        var userList = from ur in _userRuleLinks.AsQueryable()
            join u in _users.AsQueryable() on ur.UserId equals u.Id
            join r in _rules.AsQueryable() on ur.RuleId equals r.Id
            select new
            {
                UserId = u.Id,
                UserName = u.Username,
                RuleId = r.Id,
                RuleName = r.Name,
            };
        var data = from user in userList
            group user by new { user.UserId, user.UserName } into userGroup
            select new
            {
                UserId = userGroup.Key.UserId,
                UserName = userGroup.Key.UserName,
                Rules = userGroup.Select(ug => new
                {
                    RuleId = ug.RuleId,
                    RuleName = ug.RuleName
                }).ToList()
            };

        return data;
    }
}